#include "DeviceWcsHelper.h"

#include <QDebug>

#include "ModbusManager.h"
const QMap<QString, quint16> WCS_DATA_REG_MAP = {
    {"水温", 0x18}, {"PH", 0x10}, {"溶解氧", 0x14}, {"浊度", 0x16}, {"电导率", 0x12}};

bool DeviceWcsHelper::m_wcsReadFlag = false;
int DeviceWcsHelper::m_currentReadIndex = 0;
DeviceWcsHelper::DeviceWcsHelper(QString deviceName, QObject* parent) : IDevice(deviceName, parent)
{
    qDebug() << "initialized with device name:" << m_deviceName;
}

DeviceWcsHelper::~DeviceWcsHelper() { qDebug() << "destroyed for device name:" << m_deviceName; }

void DeviceWcsHelper::onGetDeviceData()
{
#ifdef QT_DEBUG
    m_deviceData.analyze_lastResult = rand() % 100000 / 1000.0;
    emit deviceDataChanged(m_deviceData);
    return;
#endif
    if (m_wcsReadFlag) {
        return;
    }

    // 轮流读取：检查是否轮到当前设备
    QStringList deviceNames = WCS_DATA_REG_MAP.keys();
    int currentDeviceIndex = deviceNames.indexOf(m_deviceName);
    if (currentDeviceIndex != m_currentReadIndex) {
        return;  // 不是当前设备的轮次
    }

    m_wcsReadFlag = true;
    ModbusHelper* modbus = ModbusManager::instance()->getModbusHelper(m_deviceName);
    if (!modbus) {
        qDebug() << "Failed to get ModbusHelper for device:" << m_deviceName;
        m_wcsReadFlag = false;
        // 切换到下一个设备
        m_currentReadIndex = (m_currentReadIndex + 1) % deviceNames.size();
        return;
    }

    if (!WCS_DATA_REG_MAP.contains(m_deviceName)) {
        qDebug() << "Device is not found:" << m_deviceName;
        m_wcsReadFlag = false;
        // 切换到下一个设备
        m_currentReadIndex = (m_currentReadIndex + 1) % deviceNames.size();
        return;
    }
    qint16 addr = WCS_DATA_REG_MAP[m_deviceName];
    modbus->asyncReadFloat(addr, 1, MB_CDAB)
        .then([this](const QVector<float>& result) {
            m_deviceData.analyze_lastResult = result[0];
            emit deviceDataChanged(m_deviceData);
        })
        .finally([this]() {
            QStringList deviceNames = WCS_DATA_REG_MAP.keys();
            // 切换到下一个设备
            m_currentReadIndex = (m_currentReadIndex + 1) % deviceNames.size();
            m_wcsReadFlag = false;
        });
}
